package com.example.demo.socket.model;


import com.example.demo.core.util.LockUtil;
import com.example.demo.core.util.ThreadUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;


/**
 * @author yj
 * @date 2021/4/6 14:07
 */
@Data
public class ChannelSession {

    private Logger logger = LoggerFactory.getLogger(ChannelSession.class);

    private final Channel channel;

    private final String channelId;

    //标记1 -- 关联设备
    private volatile String deviceScene = null;

    //标记2 -- 关联用户
    private volatile String userScene = null;

    public ChannelSession(Channel channel) {
        this.channel = channel;
        this.channelId = channel.id().asShortText();
    }

    public ChannelSession(Channel channel, String deviceScene, String userScene) {
        this.channel = channel;
        this.channelId = channel.id().asShortText();
        this.deviceScene = deviceScene;
        this.userScene = userScene;
    }

    public String getServerIp() {
        return ((InetSocketAddress) this.channel.localAddress()).getAddress().getHostAddress();
    }

    public String getClientIp() {
        return ((InetSocketAddress) this.channel.remoteAddress()).getAddress().getHostAddress();
    }


    public Boolean isActive() {
        return this.channel.isActive();
    }

    public Boolean isWrite() {
        return this.channel.isWritable();
    }

    public void close() {
        ThreadUtil.sleep(1_000);
        logger.info("断开链接");
        this.channel.close();
    }

    public void disconnect() {
        ThreadUtil.sleep(1_000);
        logger.info("断开链接");
        this.channel.disconnect();
    }

    public void writeAndFlush(String data) {
        if (isWrite()) {
            this.channel.writeAndFlush(new TextWebSocketFrame(data));
        }
    }

    public void writeAndFlush(byte[] data) {
        if (isWrite()) {
            this.channel.writeAndFlush(data);
        }
    }


}